
import UIKit

/// 微博配图视图 Cell 可重用标识符
private let StatusCellPictureViewCellId = "StatusCellPictureViewCellId"
/// 配图视图格子间距
private let StatusCellPictureItemMargin: CGFloat = 8

/// 微博配图视图
class StatusCellPictureView: UICollectionView {
    
    /// 微博视图模型
    var viewModle: StatusViewModel? {
        didSet {
            sizeToFit()
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    // MARK: - 构造函数
    init() {
        let layout = UICollectionViewFlowLayout()
        // 设置间距 默认 ItemSize 50*50
        layout.minimumInteritemSpacing = StatusCellPictureItemMargin
        layout.minimumLineSpacing = StatusCellPictureItemMargin
        
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor(white: 0.9, alpha: 1.0)
        // 注册可重用 cell
        registerClass(StatusCellPictureViewCell.self, forCellWithReuseIdentifier: StatusCellPictureViewCellId)
        // 设置数据源 - 自己重当自己的数据源
        dataSource = self
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

// MARK: - UICollectionViewDataSource
extension StatusCellPictureView: UICollectionViewDataSource {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModle?.thumbnailUrls?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusCellPictureViewCellId, forIndexPath: indexPath) as! StatusCellPictureViewCell
        
        cell.imageURL = viewModle!.thumbnailUrls![indexPath.item]
        
        return cell
    }
}

// MARK: - 视图大小
extension StatusCellPictureView {
    
    /// 计算视图大小
    private func calcViewSize() -> CGSize {
        
        // 默认每行 3 张图片
        let rowCount: CGFloat = 3
        // collectionView 总宽度
        let maxWidth = UIScreen.mainScreen().bounds.width - 2 * StatusCellMargin
                                        // *************!!! -0.01可解除9图两列问题 !!!****
        let itemWidth = (maxWidth - 2 * StatusCellPictureItemMargin) / rowCount - 0.01
        
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        // 设置itemSize
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        
        // 图片数量
        let count = viewModle?.thumbnailUrls?.count ?? 0
        
        // 1. 单图
        if count == 0 {
            return CGSizeZero
        }
        
        // 2. 单图
        if count == 1 {
            // TODO: - 临时设置单图大小
            let size = CGSize(width: 150, height: 120)
            
            layout.itemSize = size
            return size
        }
        
        // 3. 四张图，返回 2 * 2
        if count == 4 {
            let w = itemWidth * 2 + StatusCellPictureItemMargin
            return CGSize(width: w, height: w)
        }
        
        // 4. 其它
        // 行数
        let row = CGFloat((count - 1) / Int(rowCount) + 1)
        let w = rowCount * itemWidth + (rowCount - 1) * StatusCellPictureItemMargin
        let h = row * itemWidth + (row - 1) * StatusCellPictureItemMargin
        
        return CGSize(width: w, height: h)
    }
}

// MARK: - 微博配图视图 Cell
private class StatusCellPictureViewCell: UICollectionViewCell {
    
    var imageURL: NSURL? {
        didSet {
            iconView.sd_setImageWithURL(imageURL,
                placeholderImage: nil,
                options: [.RetryFailed, .LowPriority])
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        contentView.addSubview(iconView)
        iconView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 懒加载控件
    /// 图像视图
    private lazy var iconView: UIImageView = {
        let iv = UIImageView()
        
        iv.contentMode = UIViewContentMode.ScaleAspectFill
        iv.clipsToBounds = true
        
        return iv
    }()
}

